package org.chris.module;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.chris.model.MenuModel;
import org.chris.service.impl.MenuServiceImpl;
import org.chris.utils.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

@IocBean()
public class MenuModule {
	@Inject
	private MenuServiceImpl menuService;
	@At("/menu/save")
	@Ok("json")
	// 返回形式是jsp
	public void save(HttpServletRequest request) {
		try {
			String id = request.getParameter("id");
			String _parentId = request.getParameter("_parentId");
			String name = request.getParameter("name");
			String url = request.getParameter("url");
			String orderNum = request.getParameter("orderNum");
			MenuModel model = new MenuModel(StringUtils.toInt(id),StringUtils.toInt(_parentId),name,url,StringUtils.toInt(orderNum));
			this.menuService.save(model);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}
	@At("/menu/delete")
	@Ok("json")
	// 返回形式是jsp
	public void delete(HttpServletRequest request) {
		try {
			String id = request.getParameter("id");
			this.menuService.delete(StringUtils.toInt(id));
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 加载
	 * @author Chris Suk
	 * @date 2014-4-22 下午10:13:57
	 * @param request
	 */
	@At("/menu/init")
	@Ok("json")
	// 返回形式是jsp
	public Map<String, Object> init(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<MenuModel> list = new ArrayList<MenuModel>();
		try {
			list = this.menuService.init();
			List<Map<String, Object>> rows = new ArrayList<Map<String,Object>>();
			for(MenuModel model : list){
				Map<String, Object> row = new HashMap<String, Object>();
				row.put("id", model.getId());
				row.put("name", model.getName());
				row.put("url", model.getUrl());
				row.put("orderNum", model.getOrderNum());
				row.put("_parentId", model.getPId());
				rows.add(row);
			}
			map.put("total", String.valueOf(rows.size()));
			map.put("rows", rows);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
}
